<?php


namespace App\Repositories\Game\Lucky;

use App\Models\GameDB\LuckyStrike\RebateUser;
use App\Services\Tools\RedisService;
use App\Traits\Singleton;
use Carbon\Carbon;
use App\Models\MainDB\User;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;
use App\Models\MainDB\AccountLog;
use App\Repositories\UserRepository;
use Exception;


class StrikeRepositories
{
    use Singleton;

    /**
     * jjj     a 1   chu
     *  100 1     1000 10         111
     *
     *
     * 1  1  5   5 * ?    12     1000      880
     * 500
     * @param int $userId 66       33   98    500   4   999
     * @param int $number 100    1     200  2    300  3  10 99   300  99
     * 兑换 返利 礼物 币      //  每一轮 生成一个新的暴击数    99     10        1  23     66     99
     * 达标暴击 第一是否开启暴击   第二 所有的用户 累计 计数等于 随机数  达成暴击  根据投入金额 返回金币 暴击
     * 单个用户 计时器  每次暴击  投入 金额 清0   （不管奖池开了多少轮的随机数）
     * @param $automatic
     * @return bool
     * @throws BasicException
     */
    /**
     * @param int $userId
     * @param int $number
     * @param $automatic
     * @return bool
     * @throws BasicException
     * @throws Exception
     */
    public function exchange(int $userId, int $number, $automatic)
    {
        if ($automatic == 1 || $automatic == 2) {
            $automatic_new = $automatic == 2 ? 0 : $automatic;
            if ($automatic == 2) {
                RebateUser::query()->where('user_id', $userId)->update([
                    'automatic' => 0
                ]);
            } else {
                StrikeUserRepositories::getInstance()->automatic($userId, $automatic_new);
            }
            RedisService::getSaveStrikeMoney($userId, 0, 0, $automatic_new, 2);
            return true;
        }
        $setting = StrikeSettingRepository::getInstance()->setting(true);
//        if(!in_array($number, explode(',',$setting->setting))){
//            throw new BasicException(-1, "非法请求");
//        }
        DB::beginTransaction();
        DB::connection("mysql_game")->beginTransaction();
        try {     // 验证金币

            $data = RebateUser::query()->where("user_id", $userId)->first();
            if (!$data) {
                $data = [
                    'balance' => 0,
                    'output' => 0,
                    'input' => 0,
                    'to_count' => 0,
                ];
            }
            $coin = $setting->balance_coin * $number;
            $userCoin = User::query()->where("user_id", $userId)->value("money");
            if ($coin > $userCoin) { // 金币不足
                throw new BasicException(340001, "金币不足");
            }
            // 增加余额日志
            $log = StrikeBalanceLogRepository::getInstance()->swap($userId, $coin);
            // 增加余额
            StrikeUserRepositories::getInstance()->swap($userId, $coin);
            // 钱包服务
            UserRepository::getInstance()->decUserMoney($userId, $coin);
            app('model_account_log')->addLog($userId, $coin, "兑换灵珠x{$number}", AccountLog::LUCKY_REBATE, $log->id);
            // 查询
            $is = RedisService::getSaveStrikeMoney($userId, $data, $coin, $automatic);
            if (!$is) throw new BasicException(-1, "点击太快，休息一会吧");
            DB::connection("mysql_game")->commit();
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            DB::connection("mysql_game")->rollBack();
            throw new BasicException((int)$e->getCode(), $e->getMessage());
        }

        return true;
    }


    /**
     * @param $userId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws BasicException
     */
    public function setting($userId)
    {
        return StrikeSettingRepository::getInstance()->setting(true);
    }

    /**
     * @param int $userId
     * @param bool $isLock
     * @param bool $type
     * @return RebateUser|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|mixed|object|null
     */
    public function userInfo(int $userId, $isLock = false, $type = false)
    {
        $query = RebateUser::query();
        if ($isLock) {
            $query->lockForUpdate();
        }
        $redis = app('redis')->connection('game2');
        $query->where("user_id", $userId);
        if ($type) {
            // 获取金额 进行修改
            $info = $query->first();
            $key = 'rebate:user:' . $userId;
            if ($redis->exists($key)) {
                // 修改一下
                $userInfo = $redis->hgetall($key);
                $input_910 = isset($userInfo['input_910']) ? $userInfo['input_910'] : 0;
                $output_910 = isset($userInfo['output_910']) ? $userInfo['output_910'] : 0;
                $input_895 = isset($userInfo['input_895']) ? $userInfo['input_895'] : 0;
                $output_895 = isset($userInfo['output_895']) ? $userInfo['output_895'] : 0;
                $input_919 = isset($userInfo['input_919']) ? $userInfo['input_919'] : 0;
                $output_919 = isset($userInfo['output_919']) ? $userInfo['output_919'] : 0;
                $compensate_1 = isset($userInfo['compensate_910']) ? $userInfo['compensate_910'] : 0;
                $compensate_4 = isset($userInfo['compensate_895']) ? $userInfo['compensate_895'] : 0;
                $compensate_10 = isset($userInfo['compensate_919']) ? $userInfo['compensate_919'] : 0;
                $data = [
                    'balance' => $userInfo['balance'],
                    'to_count' => $userInfo['to_count'],
                    'input' => $userInfo['input'],
                    'output' => $userInfo['output'],
                    'input_910' => $output_910,
                    'output_910' => $input_910,
                    'input_895' => $input_895,
                    'output_895' => $output_895,
                    'input_919' => $input_919,
                    'output_919' => $output_919,
                    'compensate_910' => $compensate_1,
                    'compensate_895' => $compensate_4,
                    'compensate_919' => $compensate_10
                ];
                $day_key = "config:rebate:user:date:" . date("Y-m-d") . ":" . $userId;
                if ($redis->exists($day_key)) {
                    $day = app('redis')->hgetall($day_key);
                    $data['input_date'] = isset($day['input_date']) ? $day['input_date'] : 0;
                    $data['output_date'] = isset($day['input_date']) ? $day['input_date'] : 0;
                }
                $week_key = "config:rebate:user:week:" . date("Y-W") . ":" . $userId;
                if ($redis->exists($week_key)) {
                    $week = app('redis')->hgetall($week_key);
                    $data['input_week'] = isset($week['input_week']) ? $week['input_week'] : 0;
                    $data['output_week'] = isset($week['output_week']) ? $week['output_week'] : 0;
                }
                RebateUser::query()->where("user_id", $userId)->update($data);
                return isset($userInfo['balance']) ? $userInfo['balance'] : $info->balance;
            }

            return $info->balance;
        }
        $query->with([
            "date" => function ($query) {
                $query->where('date', '=', Carbon::now()->format("Y-m-d"));
                $query->select(["user_id", "count", "input", "output"]);
            }
        ]);
        $model = $query->first();
        if (!$model) {
            $model = new RebateUser();
            $model->id = 0;
            $model->user_id = $userId;
            $model->balance = 0;
            $model->input = 0;
            $model->output = 0;
            $model->save();
        }

        return $model;
    }
}
